<template>
  <div class="roles">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button
            type="primary"
            class="red_btn"
            @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表表格 -->
      <el-table :data="rolesList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级、三级权限的盒子 -->
              <el-col :span="19">
                <!-- 渲染二级权限的盒子 -->
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <!-- 渲染三级权限的盒子 -->
                    <el-tag
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="level" label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              class="btn_w green_btn"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="btn_w red_btn"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配角色按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              class="btn_w"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClosed"
      >
        <!-- 添加角色的表单验证区域 -->
        <el-form
          :model="rolesForm"
          :rules="rolesRules"
          ref="addRulesForm"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>

          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser" class="red_btn"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 修改用户信息对话框 -->
      <el-dialog
        title="修改角色信息"
        :visible.sync="editDialogVisible"
        width="40%"
        @close="editDialogClosed"
      >
        <el-form
          :model="editForm"
          :rules="rolesRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editEditInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改分配角色权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="40%"
        @close="setRightDialogClosed"
      >
        <!-- 树形控件 -->
        <el-tree
          :data="rightsList"
          :props="treeProps"
          ref="treeRef"
          node-key="id"
          :default-checked-keys="defKeys"
          show-checkbox
          default-expand-all
        ></el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "roles",
  data() {
    return {
      // *角色列表
      rolesList: [],
      //  *控制添加角色对话框的显示
      addDialogVisible: false,
      //   *角色表单
      rolesForm: {
        roleName: "",
        roleDesc: "",
      },
      // *添加角色的表单验证规则
      rolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 7,
            message: "长度在 3 到 7 个字符",
            trigger: "blur",
          },
        ],
      },
      // *控制修改角色信息的对话框是否显示
      editDialogVisible: false,
      // * 修改角色信息表单内容
      editForm: {},
      // *控制分配权限的对话框是否显示
      setRightDialogVisible: false,
      // *权限列表
      rightsList: [],
      // *权限列表的树形控件
      treeProps: {
        children: "children",
        label: "authName",
      },
      // *权限列表默认选中的三级权限的列表
      defKeys: [],
      // *当前的roleID
      roleId: "",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //   a 获取角色列表数据
    async getRolesList() {
      const res = await this.$http.get("roles");
      if (res.data.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data.data;
    },
    //*监听添加角色对话框关闭时的事件
    addDialogClosed() {
      this.$refs.addRulesForm.resetFields();
    },
    // *点击按钮添加角色
    addUser() {
      this.$refs.addRulesForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请检查填写是否正确！');
        } else {
          // a 校验值都成立 发起添加角色请求
          const res = await this.$http.post("roles", this.rolesForm);
          if (res.data.meta.status != 201) {
            return this.$message.error("添加角色失败！");
          }
          this.addDialogVisible = false;
          this.getRolesList();
          return this.$message.success("添加角色成功！");
        }
      });
    },
    // *单击编辑按钮 查询角色信息的事件
    async showEditDialog(id) {
      this.editDialogVisible = true;
      // a 根据id查询用户信息
      const res = await this.$http.get("roles/" + id);
      if (res.data.meta.status != 200) {
        return this.$message.error("查询角色信息失败");
      }
      this.editForm = res.data.data;
    },
    //  *关闭修改角色信息对话框时的事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //  *确定按钮 修改角色信息的事件
    editEditInfo() {
      // 提交修改前 校验值是否合理
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请检验角色信息是否合法！");
        }
        const res = await this.$http.put("roles/" + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc,
        });
        if (res.data.meta.status !== 200) {
          return this.$message.error("角色信息修改失败！");
        }
        this.$message.success("角色信息修改成功！"); //* 提示更新成功
        this.getRolesList(); //*更新用户列表
      });
      this.editDialogVisible = false; // *关闭对话框
    },

    //  *单击删除按钮删除角色行
    async removeRoleById(id) {
      const removeRole = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((erro) => erro);
      if (removeRole !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // a 发起删除用户请求
      const res = await this.$http.delete("roles/" + id);
      if (res.data.meta.status !== 200) {
        this.$message.error("删除角色失败!");
      }
      this.$message.success("已成功删除该角色！"); //* 提示删除成功
      this.getRolesList(); //*更新角色列表
    },

    // *根据id删除对应角色的权限（展开列）
    async removeRightById(role, rightId) {
      const removeRight = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((erro) => erro);
      if (removeRight !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // a 发起删除权限请求
      const res = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
      if (res.data.meta.status !== 200) {
        return this.$message.error("删除权限失败!");
      }
      this.$message.success("已成功删除该权限！"); //* 提示删除成功
      //   this.getRolesList(); //*更新权限列表 这里会导致页面重绘 降低用户体验
      role.children = res.data.data; //*重新赋值给children 可以删除完还停留在打开的页面
    },

    // *展示分配角色权限的对话框
    async showSetRightDialog(role) {
      // *获取分配角色权限数据
      const res = await this.$http.get("rights/tree");
      if (res.data.meta.status !== 200) {
        return this.$message.error("获取权限失败!");
      }
      this.rightsList = res.data.data;
      // *调用递归函数 获取所有三级权限放进数组
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true; //*显示分配权限对话框
      this.roleId = role.id;
    },
    // todo 递归函数 获取角色下所有三级权限的id放进数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },

    // *监听分配权限对话框关闭时的事件
    setRightDialogClosed() {
      // *清空保存三级权限id的数组
      this.defKeys = [];
    },

    // *点击对话框的确定按钮分配角色权限
    async allotRights() {
      // *将半选中和全选中的节点的id全部保存在数组中
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // *将数组变成字符串 ','分隔 用于请求分配权限
      const idStr = keys.join(",");
      // a 请求分配权限
      const res = await this.$http
      .post(`roles/${this.roleId}/rights`,{rids: idStr,});
      if(res.data.meta.status !==200){
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList() //*更新角色列表
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style scoped lang="less">
.btn_w {
  padding: 8px 10px;
  font-size: 13px;
}
.green_btn {
  background-color: rgb(36, 102, 47);
  border: 1px solid rgb(36, 102, 47);
}
.red_btn {
  background-color: rgb(196, 0, 0);
  border: 1px solid rgb(196, 0, 0);
}

.el-tag {
  margin: 15px 8px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
